package com.imooc.config;

import com.imooc.interceptor.UserTokenInterceptor;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * WebMvcConfigurer web 配置
 * 将本地资源映射到web中 在web中可以进行访问
 * addResourceHandler 映射所有资源地址
 * addResourceLocations 添加资源地址
 * addResourceLocations 支持多个
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    /**
     * 实现静态资源的映射
     * 更改了默认的映射后，需要指定引入的依赖的地址
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/META-INF/resources/")  // 映射swagger2
                .addResourceLocations("file:/workspaces/images/");  // 映射本地静态资源
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    @Bean
    public UserTokenInterceptor userTokenInterceptor() {
        return new UserTokenInterceptor();
    }

    /**
     * 注册拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 只拦截 hello 请求
        registry.addInterceptor(userTokenInterceptor())
                .addPathPatterns("/hello")
                .addPathPatterns("/shopcart/add")
                .addPathPatterns("/shopcart/del")
                .addPathPatterns("/address/list")
                .addPathPatterns("/address/add")
                .addPathPatterns("/address/update")
                .addPathPatterns("/address/setDefalut")
                .addPathPatterns("/address/delete")
                .addPathPatterns("/orders/*")
                .addPathPatterns("/center/*")
                .addPathPatterns("/userInfo/*")
                .addPathPatterns("/myorders/*")
                .addPathPatterns("/mycomments/*")         // 需要拦截
                .excludePathPatterns("/myorders/deliver") // 去除
                .excludePathPatterns("/orders/notifyMerchantOrderPaid");

        // 添加至mvc配置
        WebMvcConfigurer.super.addInterceptors(registry);
    }
}
